<template>
	<view class="login">
		<view class="title">
			赊货签助贷端
		</view>
		<!-- <view class="textH">
			电子货单
		</view> -->
		<uni-forms ref="form" :modelValue="formData" label-width="80px" :rules="rules">
			<uni-forms-item label="手机号" name="userName">
				<input type="number" v-model="formData.userName" placeholder="请输入手机号" />
			</uni-forms-item>
			<p></p>
			<uni-forms-item label="密码" name="password">
				<input type="password" v-model="formData.password" placeholder="请输入密码" />
			</uni-forms-item>
			<p></p>

			<button type="primary" @click="login">登 录</button>
			<view class="flexBox">
				<view>
					<checkbox-group @change="rememberPass">
						<label>
							<checkbox value="pass" :checked="remember" />记住密码
						</label>
					</checkbox-group>
				</view>
				<text @click="toPassword">忘记密码</text>
			</view>

			<view v-show="!showCode" class="flexBox" style="margin-bottom: 40rpx;">
				<checkbox-group @change="changeAgree">
					<label>
						<checkbox value="a" :checked="agree" />
						我已阅读并同意
					</label>
					<text @click="openAgreement" style="color: #b051ff">《用户服务协议》、</text>
					<text @click="openUse" style="color: #b051ff;">《隐私政策》</text>
				</checkbox-group>
				<!-- <text @click="openAgreement" style="color: #b051ff">《用户服务协议》、</text> 
				<text @click="openUse" style="color: #b051ff">隐私政策</text> -->
			</view>
		</uni-forms>
		<!-- <view class="funArea">
			<text @click="toRegister">没有账号? 立即注册</text>
		</view> -->
		<view class="funArea" style="display: flex;flex-direction: column;">
			<text @click="toRegister">没有账号? 立即注册</text>
			<!-- <text v-show="!isWeixinLogin" @click="otherLogin" style="margin-top: 20rpx;color: royalblue;"> <text
					style="border-bottom: 1px solid #587EF2 ;">使用其它账号登录</text> </text> -->
			<!-- 	<uni-transition ref="ani" custom-class="transition" :mode-class="modeClass" :show="isWeixinLogin">
				<view class="" v-show="isWeixinLogin" style="padding-top: 30rpx;" @click="wecartChangeLogin">
					<image style="width: 15%;height:100rpx" src="../../static/weixin.png" mode=""></image>
				</view>
			</uni-transition> -->
		</view>
	</view>
</template>

<script>
	// 引入公共接口
	import {
		// 登陆
		customUserLogin,
		// 获取用户信息
		GetAssistOperatorInfo
	} from '@/api/interface.js'
	import {
		regPhone
	} from '../../utils/regExp.js'
	export default {
		data() {
			return {
				isWeixinLogin: false,
				modeClass: 'slide-right',
				showCode: false,
				remember: true,
				agree: true, // 是否同意条款
				formData: {
					userName: '',
					password: ''
				},
				rules: {
					userName: {
						rules: [{
							required: true,
							errorMessage: '请填写手机号',
						}, {
							validateFunction: (rule, value, data, callback) => {
								if (!regPhone.test(value)) return callback('手机号格式错误')
								return true
							}
						}]
					},
					password: {
						rules: [{
							required: true,
							errorMessage: '请填写密码',
						}]
					},
				},
				weixinAuthService: {}
			}
		},
		onLoad() {
			plus.oauth.getServices((services) => {

				this.weixinAuthService = services.find((service) => {

					return service.id === 'weixin'

				})

			});
			if (!uni.getStorageSync('agree')) this.agree = false
			let pass = uni.getStorageSync('pass')
			if (pass) {
				this.formData = pass
				this.loginApi()
			}
		},
		methods: {
			handleThirdLoginApp() {
				var that = this;
				uni.getProvider({
					service: 'oauth',
					success: function(res) {
						if (~res.provider.indexOf('weixin')) {
							uni.login({
								provider: 'weixin',
								success: function(loginRes) {
									console.log('login', loginRes)
									// loginRes 包含access_token，expires_in，openid，unionid等信息
									//这里只需要把这些数据传递给后台，让后台去请求微信的接口拿到用户信息就可以了，
									//然后返回登录状态
									that.getApploginData(loginRes); //请求登录接口方法
								},

								fail: function(res) {
									that.$refs.uToast.show({
										title: '微信登录失败',
										type: 'warning'
									});
								}
							});
						}
					}
				});
			},
			otherLogin() {
				this.isWeixinLogin = !this.isWeixinLogin
			},
			// 使用其它账号登录
			wecartChangeLogin() {
				//验证有无安装微信
				let isWx = plus.runtime.isApplicationExist({
					pname: 'com.tencent.mm',
					action: 'weixin://'
				});
				if (!isWx) {
					// console.log('请先安装微信APP');
					return false;
				}
				uni.getProvider({
					service: 'oauth',
					success: (res) => {
						if (~res.provider.indexOf('weixin')) { //支持微信、qq和微博等
							uni.login({
								provider: 'weixin',
								// onlyAuthorize: true,
								success: (loginRes) => {
									console.log('uni.loginlogin是否调取成功', loginRes)
									uni.getUserInfo({
										provider: 'weixin',
										success: (userInfoRes) => {
											console.log(222, userInfoRes)
											if (userInfoRes && userInfoRes.userInfo &&
												userInfoRes.userInfo.unionId &&
												userInfoRes.userInfo.openId) {
												//可以取到用户信息
												let obj = {
													unionId: userInfoRes.userInfo
														.unionId, //unionid
													openId: userInfoRes.userInfo
														.openId, //openid
													nickName: userInfoRes.userInfo
														.nickName, //昵称
													avatarUrl: userInfoRes.userInfo
														.avatarUrl, //头像
													gender: userInfoRes.userInfo
														.gender, //性别
												}
												// console.log('[获取到的用户信息]',obj);
												addUserInfo(obj).then(res => {
													// console.log('[登录返回的参数]',obj);
													// console.log('[登录返回的参数]',res);
													if (res.code == 200) {
														uni.setStorageSync(
															'user', res
															.result)
														setTimeout(() => {
															uni.reLaunch({
																url: '/pages/index/index'
															})
														}, 1500)
														uni.showToast({
															title: '登录成功',
															duration: 3000
														});
													} else {
														uni.showToast({
															title: '登录失败',
															duration: 2000
														});
													}
												})
												return false;
											} else {
												console.log('获取信息失败11');
											}
										},
										fail: (err) => {
											console.log('获取信息失败22', err);
										}
									})
								},
								fail: (err) => {
									console.log('获取信息失败33', err);
								}
							})
						} else {
							console.log('请先安装微信APP');
						}
					},
					fail: (err) => {
						console.log('请先安装微信APP', err);
					}
				})
			},
			//请求登录接口方法

			getApploginData(data) {
				var that = this;
				//这边是前端自己去调微信用户信息的接口，根据接口需要请求，如果不需要前端去获取的话就交给后端，可省去次操作
				uni.request({
					url: 'https://api.weixin.qq.com/sns/userinfo?access_token=' + data.authResult.access_token +
						'&openid=' + data.authResult.openid,
					method: 'GET',
					dataType: 'json',
					header: {
						'content-type': 'application/x-www-form-urlencoded' // 默认值
					},

					success(res) {
						console.log('【登录回调啾啾啾】', res);
						//前端调用微信接口，获取到微信用户的基本信息，传递给后台
						that.$http('post', '/Base_Manage/Home/WxLogin', {
							OpenId: res.data.openid
						}).then(result => {

							console.log('是否微信登录成功', result.Data)
							if (result.Data.State) {
								uni.showToast({
									title: '可以跳转首页了'
								})
							} else {
								uni.showToast({
									title: '需要绑定手机号'
								})
							}

							// uni.setStorage({
							// 	data: 'Bearer ' + result.Data.Token,
							// 	key: 'token',
							// 	success: () => {
							// 		this.op()
							// 	}
							// })
							// uni.showTo
							// uni.reLaunch({
							// 	url:"/pages/Home/Home"
							// })
							// if (result.Success) {
							// 	if(result.Data.State){

							// 	}else{
							// 		uni.showToast({
							// 			title:'请绑定手机号',
							// 			icon:'none'
							// 		})
							// 	}
							// 	// uni.showToast({
							// 	// 	icon: 'none',
							// 	// 	title: result.Msg
							// 	// })
							// 	// this.showCode = true
							// } else uni.showToast({
							// 	icon: 'none',
							// 	title: result.Msg
							// })
						})
						// that.$api.wxloginThred({
						// 	unionid: data.authResult.unionid,
						// 	image: res.data.headimgurl,
						// 	nickname: res.data.nickname,
						// }).then(res => {
						// 	console.log(res)
						// 	if (res.statusCode == 200) {
						// 		uni.setStorageSync('userInfo', JSON.stringify(res.data));
						// 		uni.setStorageSync('logined', 1);
						// 		// that.$store.commit('SET_STATE', ['logined', true]);
						// 		// that.$store.commit('SET_STATE', ['userInfo', res.data]);
						// 		uni.showToast({
						// 			title: '登陆成功',
						// 			duration: 2000
						// 		});
						// 		//登录成功 跳转到首页
						// 		that.checkFirst()
						// 	}
						// });
					},
					fail() {
						uni.showToast({
							title: '微信错误',
							type: 'warning'
						})
					}
				});
			},



			openAgreement() {
				uni.navigateTo({
					url: '/pages/user/customerPage?Type=1'
				})
			},
			openUse() {
				uni.navigateTo({
					url: '/pages/webview/Use'
				})
			},
			changeAgree(e) {
				if (e.detail.value.length > 0) this.agree = true
				else this.agree = false
			},
			rememberPass(e) {
				if (e.detail.value.length > 0) this.remember = true
				else this.remember = false
			},
			// 注册
			toRegister() {
				uni.navigateTo({
					url: '/pages/Login/Register'
				})
			},
			//忘记密码
			toPassword() {
				uni.navigateTo({
					url: '/pages/Login/Password'
				})
			},
			// 登陆
			login() {
				if (!this.agree) {
					uni.showToast({
						icon: 'none',
						title: '请阅读并同意使用条款后进行登录'
					})
					return
				}
				this.$refs.form.validate().then(res => {
					this.loginApi()
				}).catch(err => {
					console.log(err);
				})
			},
			loginApi() {
				uni.showLoading({
					title:'登陆中',
					icon:'none'
				})
				customUserLogin(this.formData).then(res => {
					console.log('是否请求成功了乐乐乐了', res)
					if (res.Success) {
						setTimeout(function(){
							uni.hideLoading()
						},1000)
						
						if (this.remember) {
							uni.setStorageSync('pass', this.formData)
						}
						uni.setStorageSync('agree', true)
						uni.setStorage({
							data: 'Bearer ' + res.Data,
							key: 'token',
							success: () => {
								// 获取用户信息
								this.op()
							}
						})
					}

				}).catch((err) => {
					uni.showToast({
						icon: 'none',
						title: res.Msg
					})
				});
				// uni.showLoading()
				// this.$http('post', '/Base_Manage/Home/AssistLogin', this.formData).then(res => {
				// 	uni.hideLoading()
				// 	if (res.Success) {
				// 		if (this.remember) {
				// 			uni.setStorageSync('pass', this.formData)
				// 		}
				// 		uni.setStorageSync('agree', true)
				// 		uni.setStorage({
				// 			data: 'Bearer ' + res.Data,
				// 			key: 'token',
				// 			success: () => {
				// 				this.op()
				// 			}
				// 		})
				// 	} else uni.showToast({
				// 		icon: 'none',
				// 		title: res.Msg
				// 	})
				// })
			},
			// 用户信息
			op() {
				GetAssistOperatorInfo().then(res=>{
					console.log('是否获取用户信息成功', res)
					if (res.Success) {
						uni.setStorageSync('userInfo', res.Data.UserInfo)
						uni.switchTab({
							url: '/pages/index/index'
						})
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.flex {
		display: flex;
		margin-top: 40rpx;
		text-align: center;
		color: #a6a6a6;
		font-size: 15px;
		margin-left: 20px;
	}

	.login {
		padding: 40rpx;
		width: 100%;
		height: 100%;
		background: url('@/static/bj.jpg') no-repeat center center fixed;
		background-size: cover;
		box-sizing: border-box;

		.flexBox {
			margin-top: 40rpx;
			box-sizing: border-box;
			padding: 10rpx 40rpx;
			display: flex;
			justify-content: space-between;
		}

		.title {
			text-align: center;
			font-size: 70rpx;
			font-weight: bolder;
			color: #fff;
			margin-top: 30rpx;
			margin-bottom: 3%;
			line-height: 4;
		}

		.textH {
			text-align: center;
			font-size: 40rpx;
			font-weight: 500;
			color: #fff;
			margin-bottom: 90rpx;
		}

		.uni-forms {
			background-color: #fff;
			display: flexbox;
			border-radius: 17px;
			padding: 20px 0;
		}

		.uni-forms-item {
			color: #000;
			padding: 10rpx 20rpx 10rpx 33rpx;
			display: flex;
			align-items: center;
			margin-bottom: 20rpx;
		}

		/deep/.uni-forms-item__label {
			display: flex;
			flex-direction: row;
			align-items: center;
			text-align: left;
			font-size: 16px;
			font-weight: bold;
			color: #7d8084;
			height: 36px;
			padding: 0 12px 0 0;
			vertical-align: middle;
			flex-shrink: 0;
			box-sizing: border-box;
		}

		/deep/.uni-forms-item__error {
			color: #f56c6c;
			font-size: 12px;
			line-height: 2.9;
		}


		p {
			border-bottom: 1px solid #d5d5d5;
			width: 92%;
			margin: 0 auto;
			margin-bottom: 5%;
			margin-top: -2%;
		}

		h6 {
			text-align: right;
			font-size: 15px;
			font-weight: bold;
			color: #6d7073;
			padding: 0 60rpx;

		}

		button {
			width: 90%;
			border-radius: 100rpx;
			font-size: 20px;
			font-weight: bold;
			margin-top: 40rpx;
			background: linear-gradient(to left, #972ae7, #687bf1);

		}

		.funArea {
			margin-top: 65rpx;
			text-align: center;
			color: #fff;
			font-size: 15px;
			font-weight: bold;
		}
	}
</style>